package com.tanhua.sso.controller;

import com.tanhua.sso.service.SmsService;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

   /* @PostMapping("/login")
    public String sendCheckCode(@RequestBody Map<String,String> param){
        String phone = param.get("phone");//获取手机号码
        //System.out.println(phone);
        String code = this.redisTemplate.opsForValue().get(phone);//获取redis中当前手机号对应的验证码
        if (!StringUtils.isEmpty(code)){
            return phone + ":" + code + "未过期";
        }else {
            //生成验证码并存储到redis中
            code = this.smsService.sendSms(phone);
            this.redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return phone + ":" + code + "发送成功";
        }
        //String code = this.loginService.sendSms(phone);
        //System.out.println(code);
        //return code;
    }*/

    /**
     * 发送短信验证码接口
     *
     * @param param
     * @return
     */
    @PostMapping("/login")
    public ResponseEntity<ErrorResult> sendCheckCode(@RequestBody Map<String, String> param) {
        ErrorResult errorResult = null;
        String phone = param.get("phone");
        try {
            errorResult = smsService.sendCheckCode(phone);
            //如果errorResult返回为空,则说明service执行成功
            if (null == errorResult) {
            //响应200状态码,响应体中为空,相当于response.setStatus(200);
                return ResponseEntity.ok(null);
            }
        } catch (Exception e) {
        //service调用抛出的异常
        //这里必须要抓起来,或者写一个全局异常处理器
            log.error("发送短信验证码失败~ phone = " + phone, e);
            //000002 没有意义,自己定义,写什么都可以
            //在实际开发中,每个项目中都有很多自己定义的状态码
            errorResult = ErrorResult.builder().errCode("000002").errMessage("短信验证码发送失败！").build();
        }
        //如果有异常就响应一个500状态码
        //相当于response.setStatus(500),并且响应errMessage,mvc会自动转换为json,
        //前台拿到的数据是: 响应状态码是500,响应体中是{errCode:"000002",errMessage:"短信验证码发送失败！"}
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }
}
